<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="内容分类" prop="fileType">
        <!-- <el-select v-model="queryParams.type" placeholder="请选择内容分类" clearable style="width: 240px">
            <el-option v-for="dict in dict.type.sys_video_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>  -->
          <el-select v-model="queryParams.fileType" placeholder="请选择内容分类" clearable>
            <el-option v-for="(item, index) in typeOptions" :key="index" :label="item.label"
            :value="item.value" :disabled="item.disabled"></el-option>
              </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:sysData:add']"
        >上传同步内容</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="sysDataList" @selection-change="handleSelectionChange">
      <el-table-column label="编号" align="center" prop="id"  width="80"/>
      <el-table-column label="内容分类" align="center" prop="fileType"   >
      <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_data_fileType" :value="scope.row.fileType"/>
        </template>
      </el-table-column>
      <el-table-column label="内容上传地址" align="center" prop="url"   />
      <el-table-column label="创建时间" align="center" prop="createTime"  >
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
              </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:sysData:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改内容导入对话框 -->
    <el-dialog :title="title" :visible.sync="upload.open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="内容分类" prop="fileType">
          <el-select v-model="form.fileType" placeholder="请选择内容分类">
            <el-option v-for="(item, index) in typeOptions" :key="index" :label="item.label"
            :value="item.value" :disabled="item.disabled"></el-option>
              </el-select>
        </el-form-item>
        <el-form-item label="文件上传" prop="uploadFile">
      <el-upload ref="upload" :limit="1" accept=".zip" 
      :headers="upload.headers" 
      :action="upload.url + '?fileType=' + form.fileType" 
      :disabled="upload.isUploading" 
      :on-progress="handleFileUploadProgress" 
      :on-success="handleFileSuccess" 
      :on-error="handleFileError"
      :auto-upload="false">
      <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
      </el-upload>
      <!-- 显示上传进度 -->
      <div v-if="upload.progress > 0 && upload.progress < 100">上传进度: {{ upload.progress }}%</div>
    </el-form-item>
    <span class="file-upload-tip">支持导入压缩包文件,仅允许zip格式文件</span>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
        <!-- 遮罩层和进度提示 -->
        <div v-if="upload.isProcessing" class="upload-mask">
      <div class="upload-progress">
        <div class="progress-bar" :style="{ width: upload.progress + '%' }"></div>
        <p>{{ upload.processingMessage }}</p>
      </div>
    </div>
  </div>
</template>

<script>
import { listSysData, getSysData, delSysData, addSysData, updateSysData } from "@/api/system/sysData";
import { getToken } from "@/utils/auth";

export default {
  name: "SysData",
  dicts: ['sys_data_fileType', 'sys_user_sex','sys_board_data','sys_channel_status','sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 内容导入表格数据
      sysDataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        url: null,
        name: null,
        operatorName: null,
        fileType: null,
        remarks: null,
        status: null,
        operatorVersion: null,
        synchUrl: null,
        unzipUrl: null,
        synchFlag: null
      },
      typeOptions: [{
        "label": "电影",
        "value": "1"
      }, {
        "label": "音乐",
        "value": "2"
      }],
      // 表单参数
      form: {},
      // 文件导入参数
      upload: {
        // 是否显示弹出层（文件导入）
        open: false,
        // 弹出层标题（文件导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/sysData/uploadFile",
        progress: 0,
        processingMessage: "文件上传处理中",
         // 遮罩层显示状态
         isMaskVisible: false
      },
      // 表单校验
      rules: {
        fileType: [
          { required: true, message: "内容分类不能为空", trigger: "blur" },
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询内容导入列表 */
    getList() {
      this.loading = true;
      listSysData(this.queryParams).then(response => {
        this.sysDataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.upload.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        createTime: null,
        url: null,
        name: null,
        operatorName: null,
        fileType: null,
        remarks: null,
        status: null,
        operatorVersion: null,
        synchUrl: null,
        unzipUrl: null,
        synchFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.upload.open = true;
      this.title = "添加内容导入";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSysData(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改内容导入";
      });
    },
    simulateProcessing(message, duration) {
      this.upload.processingMessage = message;
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve();
        }, duration);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      console.log("文件上传中:"+JSON.stringify(event));
      this.upload.isUploading = true;
      this.upload.isProcessing = true;
      this.upload.progress = Math.round(event.percent);
      this.upload.processingMessage = '文件上传处理中';
    },
        // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      console.log("文件上传结果"+JSON.stringify(response));
      this.upload.open = false;
      this.upload.isUploading = false;
      this.upload.progress = 0;
      this.$refs.upload.clearFiles();
      this.getList();
      
      if (response.code == 200) {
        this.simulateProcessing('文件解压中', 3000);
        this.simulateProcessing('文件解析中', 3000);
        this.upload.isProcessing = false;
        this.$modal.alertSuccess(response.msg);
      } else {
        this.$modal.alertError('上传失败:'+response.msg);
        this.upload.isProcessing = false;
      }
    },
      // 文件上传失败处理
    handleFileError(error, file, fileList) {
      console.log("文件上传失败"+JSON.stringify(error));
      this.upload.isUploading = false;
      this.upload.progress = 0;
      this.upload.isProcessing = false;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSysData(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            console.log("文件上传,点击确定按钮");
            const uploadFiles = this.$refs.upload.uploadFiles;
            console.log("文件个数:"+uploadFiles.length);
            if (uploadFiles.length === 0) {
              this.$message.error('请选择要升级的压缩包文件');
              return;
            }
            // 显示遮罩层
            this.upload.isMaskVisible = true;
            this.upload.isProcessing = true;
            this.$refs.upload.submit();
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除内容导入编号为"' + ids + '"的数据项？').then(function() {
        return delSysData(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
  }
};
</script>

<style scoped>
.upload-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999; /* 增加z-index确保覆盖所有元素 */
}

.upload-progress {
  background-color: white;
  padding: 10px;
  border-radius: 2px;
  width: 75%;
  text-align: center;
}

.progress-bar {
  height: 10px;
  background-color: #2196F3;
  width: 0%;
  border-radius: 2px;
  margin-bottom: 5px;
}

/* 新增的样式，设置span元素的样式 */
.file-upload-tip {
  font-weight: bold; /* 加粗 */
  color: red; /* 红色 */
  text-align: center;
}
</style>
